package com.anolesoft.amljmes.test.fenguangyingdu.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.anolesoft.amljmes.billing.dto.AmBillingInfoExportDTO;
import com.anolesoft.amljmes.test.fenguangyingdu.dto.FabrecordDTO;
import com.anolesoft.amljmes.test.fenguangyingdu.dto.FenguangYingduEmpDTO;
import com.anolesoft.amljmes.test.fenguangyingdu.dto.FenguangYingduRecordDTO;
import com.anolesoft.amljmes.test.fenguangyingdu.dto.FenguangYingduRecordQueryDTO;
import com.anolesoft.amljmes.test.fenguangyingdu.vo.FabrecordVO;
import com.anolesoft.amljmes.test.fenguangyingdu.vo.FenguangYingduRecordExcelVO;
import com.anolesoft.common.SacmesConfig;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.amljmes.test.fenguangyingdu.service.FenguangYingduService;
import com.anolesoft.amljmes.test.fenguangyingdu.vo.FenguangYingduRecordQueryVO;
import com.anolesoft.amljmes.test.fenguangyingdu.vo.FenguangYingduRecordVO;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhj
 * @date 2021/12/22 11:33
 */
@RestController
@Slf4j
@RequestMapping("/api/fengguangyingdurecord")
public class FengguangYingduController {
    @Autowired
    private FenguangYingduService fenguangYingduService;

    @GetMapping(value = "/list")
    public AjaxResult selectPageConditonList(FenguangYingduRecordQueryVO fenguangYingduRecordQueryVO) {
        log.debug("fenguangYingduRecordQueryVO：{}", fenguangYingduRecordQueryVO);
        Integer limit = fenguangYingduRecordQueryVO.getPageSize();
        Integer curr = fenguangYingduRecordQueryVO.getPageNo();
//        PageData<List<CrmBasePartPriceQueryDTO>> pageData = crmBasePartPriceService.selectPageConditionList(crmBasePartPriceQueryDTO, limit, curr);
//        List<CrmBasePartPriceQueryVO> vos = pageData.getItems().stream().map(t -> CustomBeanUtils.crmBasePartPriceQueryDTO2VO(t)).collect(Collectors.toList());
//        PageInfo<List<CrmBasePartPriceQueryVO>> pageInfo = new PageInfo<>(limit, pageData.getTotal(), vos);
        FenguangYingduRecordQueryDTO dto = BeanUtil.copyProperties(fenguangYingduRecordQueryVO, FenguangYingduRecordQueryDTO.class);
        log.debug("{}", dto);
        PageData<List<FenguangYingduRecordQueryDTO>> listPageData = this.fenguangYingduService.selectListByCondition(dto, limit, curr);
        List<FenguangYingduRecordQueryVO> vos = listPageData.getItems().stream().map(t -> BeanUtil.copyProperties(t, FenguangYingduRecordQueryVO.class)).collect(Collectors.toList());
        PageResult pg = new PageResult(vos, limit, curr, listPageData.getTotal());
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, pg);
    }

    @GetMapping(value = "/fabrecord")
    public AjaxResult selectPageConditonList(@RequestParam("zhizaojilutiaoma") String zhizaojilutiaoma) {
        FabrecordDTO fabrecordDTO = fenguangYingduService.queryFabrecordByCode(zhizaojilutiaoma);
        if (Objects.isNull(fabrecordDTO)) {
            return new AjaxResult(HttpStatus.ERROR, "未找到对应制造记录！");
        }
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, BeanUtil.copyProperties(fabrecordDTO, FabrecordVO.class));
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class FenguangYingduRecordFormVO {
        private String jianyantiaoma;
        private List<FenguangYingduRecordVO> fenguangYingduRecordVOs;
    }

    @PostMapping
    public AjaxResult saveBatch(@RequestBody FenguangYingduRecordFormVO form) {
        ///api/fengguangyingdurecord
        log.debug("save data:{}", form);
        FenguangYingduEmpDTO fenguangYingduEmpDTO = this.fenguangYingduService.queryCheckByCode(form.jianyantiaoma);
        if (Objects.isNull(fenguangYingduEmpDTO)) {
            return new AjaxResult(HttpStatus.ERROR, "未找到对应检验信息！");
        }
        List<FenguangYingduRecordDTO> dtos = form.fenguangYingduRecordVOs.stream().map(t -> {
            FenguangYingduRecordDTO dto = BeanUtil.copyProperties(t, FenguangYingduRecordDTO.class);
            dto.setJianbiaotiaoma(form.jianyantiaoma);
            dto.setCreateUser(fenguangYingduEmpDTO.getObjuid());
            dto.setJianyan(fenguangYingduEmpDTO.getObjuid());
            return dto;
        }).collect(Collectors.toList());
        this.fenguangYingduService.createBatch(dtos);
        return new AjaxResult(HttpStatus.SUCCESS, "保存成功");
    }

    @PutMapping("/state/{state}")
    public AjaxResult modifyStateBatch(@RequestBody List<String> ids, @PathVariable("state") Integer state) {
        log.debug("{},{}", ids, state);
        this.fenguangYingduService.modifyState(ids, state);
        return AjaxResult.success("申请成功");
    }

    @PutMapping
    public AjaxResult update(@RequestBody FenguangYingduRecordVO vo) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.debug("FenguangYingduRecord update:{}", vo);
        this.fenguangYingduService.modify(BeanUtil.copyProperties(vo, FenguangYingduRecordDTO.class));
        return AjaxResult.success("申请成功");
    }

    @PostMapping("/excel")
    public void export(FenguangYingduRecordQueryVO fenguangYingduRecordQueryVO, HttpServletResponse response) {
        log.debug("fenguangYingduRecordQueryVO导出excel：{}", fenguangYingduRecordQueryVO);
        FenguangYingduRecordQueryDTO dto = BeanUtil.copyProperties(fenguangYingduRecordQueryVO, FenguangYingduRecordQueryDTO.class);
        List<FenguangYingduRecordQueryDTO> listData = this.fenguangYingduService.selectListByCondition(dto);
        List<FenguangYingduRecordQueryVO> vos = listData.stream().map(t -> BeanUtil.copyProperties(t, FenguangYingduRecordQueryVO.class)).collect(Collectors.toList());


        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        try(OutputStream out = response.getOutputStream()) {
            EasyExcel.write(out, FenguangYingduRecordExcelVO.class)
                    .registerConverter(new LocalDateTimeConverter())
                    .sheet("分光硬度检查").doWrite(vos);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String encodingFilename(String filename) {
        filename = CommonUtils.fastUUID() + "_" + filename + ".xlsx";
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    private String getAbsoluteFile(String filename) {
        String downloadPath = SacmesConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
}
